package com.xuhuan.practice.utils;

import com.xuhuan.practice.properties.JWTProperties;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

/**
 * @author: huan.xu
 * @create: 2023/12/23 15:33
 * @description: redis工具类
 **/
@Slf4j
public class RedisUtil {

  private RedisUtil() {
  }

  private static JWTProperties jwtProperties;
  private static StringRedisTemplate stringRedisTemplate;

  static {
    RedisUtil.jwtProperties = SpringContextUtil.getBean(JWTProperties.class);
    RedisUtil.stringRedisTemplate = SpringContextUtil.getBean(StringRedisTemplate.class);
  }

  /**
   * 设置JWT的token
   *
   * @param key
   * @param value
   */
  public static void setJWTStringKey(String key, String value) {
    setExpiresStringKey(key, value, Long.valueOf(jwtProperties.getExpiresHour()), TimeUnit.HOURS);
  }

  /**
   * 设置过期的key
   *
   * @param key
   * @param value
   * @param timeOut 过期时长
   * @param unit    过期时长单位
   */
  public static void setExpiresStringKey(String key, String value, Long timeOut, TimeUnit unit) {
    ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
    operations.set(key, value, timeOut, unit);
  }

  /**
   * 设置值
   *
   * @param key
   * @param value
   */
  public static void setStringKey(String key, String value) {
    ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
    operations.set(key, value);
  }

  /**
   * 获取值
   *
   * @param key
   */
  public static String getStringKey(String key) {
    ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
    return operations.get(key);
  }

  /**
   * 删除值
   *
   * @param key
   */
  public static void delKey(String key) {
    ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
    operations.getOperations().delete(key);
  }

}
